package com.lkd.http.controller;

import com.github.wxpay.plus.WXConfig;
import com.github.wxpay.plus.WxPayTemplate;
import com.lkd.exception.LogicException;
import com.lkd.service.OrderService;
import com.lkd.vo.PayVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Slf4j
@RestController
public class OrderController {

    @Autowired
    private OrderService orderService;
    @Autowired
    private WxPayTemplate wxPayTemplate;
    @Autowired
    private WXConfig wxConfig;


    /**
     * 创建订单
     * @param payVO
     * @return
     */
    @PostMapping("/order/requestPay")
    public Map<String, String> requestPay(@RequestBody PayVO payVO){
        return orderService.createOrder(payVO);
    }


    @RequestMapping("/order/payNotify")
    public void payNotify(HttpServletRequest request,
                          HttpServletResponse response){
//        验证支付通知参数
        try {
            Map<String, String> map = wxPayTemplate.validPay(request.getInputStream());
            if(CollectionUtils.isEmpty(map) || "FAIL".equals(map.get("code"))){
                log.error("支付通知参数验证异常");
                throw new LogicException("通知参数验证异常");
            }
            log.info("得到支付通知={}",map);
//            修改订单状态
            orderService.payNotify(map);
            //给微信支付一个成功的响应
            response.setContentType("text/xml");
            response.getWriter().write(WXConfig.RESULT);
        } catch (Exception e) {
            e.printStackTrace();
            throw new LogicException("通知参数验证异常");
        }


    }
}
